package edu.whcp.comp2301.controller;

import edu.whcp.comp2301.dao.CategoryDao;
import edu.whcp.comp2301.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/list")
public class CategoryController {
    @Autowired
    private CategoryDao categoryDao;

    @RequestMapping("/category")
    public ModelAndView getAllCategories(){
        List<Category> categoryList=categoryDao.getAllCategories();
        return new ModelAndView("backend/type-management","categoryList",categoryList);
    }

    @RequestMapping(value = "/get/category",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<Category> getCategoryList(){
        return categoryDao.getAllCategories();
    }

    @RequestMapping(value = "/add/category",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Integer addCategory(Category category){
        categoryDao.addCategory(category);
        return 1;
    }

    @RequestMapping(value = "/edit/category/{id}",produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String showCategory(@PathVariable String id){
        Category category=categoryDao.getCategoryById(id);
        return category.getName();
    }

    @PostMapping(value = "/edit/category",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Integer editCategory(Category category){
        categoryDao.editCategory(category);
        return 1;
    }

    @PostMapping("/del/category/{id}")
    public String delCategory(@PathVariable String id){
        categoryDao.delCategoryById(id);
        return "redirect:/list/category";
    }

    @RequestMapping(value = "/get/category/news",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public int getCategoryNewsNum(@RequestParam String id){
        return categoryDao.queryNewsNumByCategoryId(id);
    }
}